package org.webdb.webapp.resteasy;

import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.HttpResponse;
import org.jboss.resteasy.spi.InjectorFactory;
import org.jboss.resteasy.spi.PropertyInjector;
import org.jboss.resteasy.spi.ResourceFactory;
import org.picocontainer.ComponentAdapter;
import org.webdb.webapp.picocontainer.PicoRegistry;

public class PicoResourceFactory implements ResourceFactory {

    private PropertyInjector injector = null;
    private Class<?> scanneableClass;
    private Object componentKey;

    public PicoResourceFactory(ComponentAdapter<?> adapter) {
        this.componentKey = adapter.getComponentKey();
        this.scanneableClass = adapter.getComponentImplementation();
    }

    @Override
    public Class<?> getScannableClass() {
        return scanneableClass;
    }

    @Override
    public void registered(InjectorFactory factory) {
        injector = factory.createPropertyInjector(scanneableClass);
    }

    @Override
    public Object createResource(HttpRequest request, HttpResponse response,
            InjectorFactory factory) {
        Object resource = PicoRegistry.getRequestContainer().getComponent(
                componentKey);

        injector.inject(request, response, resource);
        return resource;
    }

    @Override
    public void requestFinished(HttpRequest request, HttpResponse response,
            Object resource) {
    }

    @Override
    public void unregistered() {

    }

}
